#include<stdio.h>
#include<stdlib.h>
#include<assert.h>

// 列表类
typedef struct 
{
    int *arr;
    int capacity;
    int size;
    int extendRatio; // 每次扩容的倍数
}MyList;

/* 构造函数 */ 
MyList *newMyList()
{
    MyList *p = (MyList *)malloc(sizeof(MyList));
    p->capacity = 10;
    p->arr = (int *)malloc(p->capacity * sizeof(int));
    p->size = 0;
    p->extendRatio = 2;
    return p;
}
/* 析构函数 */ 
void delMyList(MyList *p)
{
    free(p->arr);
    free(p);
}
/* 获取列表长度 */
int size(MyList *p)
{
    return p->size;
}
/* 获取列表容量 */ 
int capacity(MyList *p)
{
    return p->capacity;
}
/* 列表访问元素 */ 
int get(MyList *p, int idx)
{
    assert(idx >= 0 && idx < p->size);
    return p->arr[idx];
}
/* 更新元素 */  
void set(MyList *p, int idx, int val)
{
    assert(idx >= 0 && idx < p->size);
    p->arr[idx] = val;
}
/*扩容数组*/ 
void extendCapacity(MyList *p)
{
    p->capacity = p->capacity*p->extendRatio;
    int *nums = (int *)malloc(p->capacity*sizeof(int));
    for (int i = 0; i < p->size; i++)
    {
        nums[i] = p->arr[i];
    }
    free(p->arr);
    p->arr = nums;
}
/* 在尾部添加元素 */
void add(MyList *p, int val)
{
    int size = p->size;
    if (size == p->capacity)
    {
        extendCapacity(p);
    }
    p->arr[size] = val;
    p->size++;
}
/* 在中间插入元素 */
void insert(MyList *p, int idx, int val)
{
    int size = p->size;
    if (size == p->capacity)
    {
        extendCapacity(p);
    }
    for (int i = size; i > idx; i--)
    {
        p->arr[i] = p->arr[i-1];
    }
    p->arr[idx] = val;
    p->size++;
}
/*删除元素*/
void removeItem(MyList *p, int idx)
{
    for (int i = idx; i < p->size-1; i++)
    {
        p->arr[i] = p->arr[i+1];
    }
    p->size--;
}
/* 将列表转换为 Array 用于打印 */
int *toArray(MyList *p)
{
    return p->arr;
}
/*打印*/
void printList(MyList *p)
{
    for (int i = 0; i < p->size; i++)
    {
        printf("%d,", p->arr[i]);
    }
    printf("\n");
}

int main(int argc, char const *argv[])
{
    // 初始化
    MyList *nums = newMyList();
    add(nums, 1);
    add(nums, 2);
    add(nums, 3);
    add(nums, 4);
    printList(nums);
    // 扩容
    extendCapacity(nums);
    printf("cap:%d\n", nums->capacity);
    // insert
    insert(nums, 1, 9999);
    printList(nums);
    // 删除
    removeItem(nums, 1);
    printList(nums);
}

